package com.cskaoyan.gateway.controller.cart;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.form.cart.AddCartForm;
import com.cskaoyan.gateway.form.cart.CheckItemAllForm;
import com.cskaoyan.gateway.form.cart.UpdateCartForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/shopping")
public class CartController {
    @Reference(timeout = 3000,retries = 0, check = false)
    ICartService iCartService;
    /**
     * /shopping/carts GET 获取购物车列表
     */

    @GetMapping("carts")
    public ResponseData cartList(HttpServletRequest request){
        HashMap<String,Object> userInfo = (HashMap<String, Object>) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        long uid = (long) userInfo.get("uid");

        CartListByIdRequest cartListByIdRequest = new CartListByIdRequest();
        cartListByIdRequest.setUserId(uid);

        CartListByIdResponse cartResponse = iCartService.getCartListById(cartListByIdRequest);

        if (cartResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(cartResponse.getCartProductDtos());
        }
        return new ResponseUtil().setErrorMsg(cartResponse.getMsg());
    }

    /**
     * 添加购物车商品
     * /shopping/carts POST
     * {"userId":"62","productId":100053202,"productNum":1}
     */
    @PostMapping("carts")
    public ResponseData cartAdd(@RequestBody AddCartForm form,HttpServletRequest servletRequest){
        log.debug(form.toString());
        AddCartRequest request = new AddCartRequest();
        HashMap<String,Object> userInfo = (HashMap<String, Object>) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        Long uid = (long) userInfo.get("uid");

        //这个地方需要做前端传来的userId和真正目前ServletRequest里的userId做对比，比较么
        if(!uid.equals(form.getUserId())){
            log.info("前端用户id:"+form.getUserId()+"servletRequest里的用户id："+uid);
            return new ResponseUtil<>().setErrorMsg("用户id不一致！");
        }
        request.setUserId(uid);
        request.setItemId(form.getProductId());
        request.setNum(form.getProductNum());

        AddCartResponse response = iCartService.addToCart(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());

    }


    /**
     * 更新购物车中的商品信息
     * /shopping/carts PUT
     * {userId: "62", productId: 100053312, productNum: 3, checked: "true"}
     */

    @PutMapping("carts")
    public ResponseData cartsUpdate(@RequestBody UpdateCartForm form, HttpServletRequest servletRequest){
        UpdateCartNumRequest request = new UpdateCartNumRequest();
        HashMap<String,Object> userInfo = (HashMap<String, Object>) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        Long uid = (long) userInfo.get("uid");
        if(!uid.equals(form.getUserId())){
            log.info("前端用户id:"+form.getUserId()+"servletRequest里的用户id："+uid);
            return new ResponseUtil<>().setErrorMsg("用户id不一致！");
        }
        request.setUserId(form.getUserId());
        request.setItemId(form.getProductId());
        request.setNum(form.getProductNum());
        request.setChecked(form.getChecked());
        UpdateCartNumResponse response = iCartService.updateCartNum(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * /shopping/carts/{uid}/{pid}      DELETE
     * long uid：用户id，long pid：商品id（itemId）
     * {"success":true,"message":"success","code":200,"result":"成功","timestamp":1587794411224}
     */
    @DeleteMapping("/carts/{uid}/{pid}")
    public ResponseData deleteCart(@PathVariable("uid") Long uid,@PathVariable("pid") Long pid, HttpServletRequest servletRequest){
        DeleteCartItemRequest request = new DeleteCartItemRequest();
        HashMap<String,Object> userInfo = (HashMap<String, Object>) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        Long userId = (long) userInfo.get("uid");
        if(!uid.equals(userId)){
            log.info("前端用户id:"+uid+"servletRequest里的用户id："+userId);
            return new ResponseUtil<>().setErrorMsg("用户id不一致！");
        }
        request.setUserId(uid);
        request.setItemId(pid);
        DeleteCartItemResponse response = iCartService.deleteCartItem(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * /shopping/items/{id}  DELETE
     * id大概是用户id...
     * {"success":true,"message":"success","code":200,"result":"成功","timestamp":1587795935665}
     */
    @DeleteMapping("/items/{id}")
    public ResponseData deleteCheckedItem(@PathVariable("id")Long id,HttpServletRequest servletRequest){
        DeleteCheckedItemRequest request = new DeleteCheckedItemRequest();
        HashMap<String,Object> userInfo = (HashMap<String, Object>) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        Long userId = (long) userInfo.get("uid");
        if(!userId.equals(userId)){
            log.info("前端用户id:"+id+"servletRequest里的用户id："+userId);
            return new ResponseUtil<>().setErrorMsg("用户id不一致！");
        }
        request.setUserId(id);
        DeleteCheckedItemResposne response = iCartService.deleteCheckedItem(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * /shopping/items PUT
     * 全选购物车中的商品
     * 请求参数：{"userId":"74","checked":"false"}
     * 返回参数：{"success":true,"message":"success","code":200,"result":"成功","timestamp":1632805888361}
     */
    @PutMapping("/items")
    public ResponseData checkAllItems(@RequestBody CheckItemAllForm form,HttpServletRequest servletRequest){
        CheckAllItemRequest request = new CheckAllItemRequest();
        Long userId = form.getUserId();
        String checked = form.getChecked();
        request.setUserId(userId);
        request.setChecked(checked);
        CheckAllItemResponse response = iCartService.checkAllCartItem(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }




}